package com.hca.training.zk.javabasic.Socket.Socket_Test;

import java.io.*;

import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Date;

public class TcpServer {
    private static  final  int BUFSIZE=32;
    public static void  main(String[] arg0) throws IOException, IllegalAccessException {
        String[] ar={"8800"};
        runs(ar);
    }
    public static void  runs(String[] arg0) throws IllegalAccessException, IOException {
        if (arg0.length!=1)
        {
            throw new IllegalAccessException("参数(s):<端口>");
        }
        int servPort=Integer.parseInt(arg0[0]);
        int recvMsgSize;
        //创建服务器套接字
        ServerSocket serverSocket=new ServerSocket(servPort);
        byte[] receiveBuf=new byte[BUFSIZE];
        System.out.println("--   服务器上已线  --");
        //一直监听迭代处理请求
        while (true)
        {
            Socket socket=serverSocket.accept();
            SocketAddress socketAddress=socket.getRemoteSocketAddress();
            System.out.println("握手连接正在建立。。。。"+socketAddress);
            InputStream inputStream= socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String client_info = null;
            while((client_info=br.readLine())!=null){
                System.out.println("客户端传过来的值："+client_info);
            }

            //测试：将当前时间写入流中返回给客户端
            Writer writer = new OutputStreamWriter(socket.getOutputStream());
            String nowData = new Date().toString();
            writer.write("服务端当前时间为——"+nowData);
            writer.flush();
            System.out.println("开始关闭socket连接。。。");
            socket.close();
        }
    }
}
